package com.skynet.supervision.es;

import com.skynet.supervision.es.domain.FileObj;
import com.skynet.supervision.utils.TimeUtils;
import com.skynet.supervision.utils.UuidUtils;
import lombok.SneakyThrows;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

public class FileOperation {

    @SneakyThrows
    public static FileObj readFile(MultipartFile file) {
        //读文件
        FileObj fileObj = new FileObj();
        fileObj.setId(UuidUtils.randomUUID());
        fileObj.setName(file.getName());
        fileObj.setType(file.getName().substring(file.getName().lastIndexOf(".") + 1));
        fileObj.setCreateTime(TimeUtils.currentTime());
        byte[] bytes = getContent(file);

        //将文件内容转化为base64编码
        String base64 = Base64.getEncoder().encodeToString(bytes);
        fileObj.setContent(base64);

        return fileObj;
    }

    @SneakyThrows
    private static byte[] getContent(MultipartFile file) {

        long fileSize = file.getSize();
        if (fileSize > Integer.MAX_VALUE) {
            System.out.println("file too big...");
            return null;
        }
        InputStream fi = file.getInputStream();
        byte[] buffer = new byte[(int) fileSize];
        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length
                && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
            offset += numRead;
        }
        // 确保所有数据均被读取
        if (offset != buffer.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }
        fi.close();
        return buffer;
    }
}
